<template>
  <div class="paper-manage">
    <div class="header">
      <el-button type="primary" @click="showCreateDialog" :icon="Plus">新增试卷</el-button>
    </div>
    <el-table :data="paperStore.papers" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="试卷标题"></el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
      <el-table-column prop="questionIds" label="试题数量" width="120">
        <template #default="{ row }">
          {{ row.questionIds?.length || 0 }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          {{ statusMap[row.status] || row.status }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="showEditDialog(row)"
            :icon="Edit"
          >修改</el-button>
          <el-button
            v-if="row.status === 'DRAFT'"
            type="success"
            size="small"
            @click="publishPaper(row.id)"
            :icon="Check"
          >发布</el-button>
          <el-button
            type="danger"
            size="small"
            @click="paperStore.deletePaper(row.id)"
            :icon="Delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增试卷对话框 -->
    <el-dialog title="新增试卷" v-model="createDialogVisible" width="40%">
      <el-form :model="createForm" label-width="80px" :rules="formRules" ref="createFormRef">
        <el-form-item label="试卷标题" prop="title">
          <el-input v-model="createForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="createForm.description" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="试题" prop="questionIds">
          <el-select
            v-model="createForm.questionIds"
            multiple
            placeholder="请选择试题"
            style="width: 100%"
          >
            <el-option
              v-for="question in questionStore.questions"
              :key="question.id"
              :label="question.title"
              :value="question.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createPaper" :icon="Plus">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改试卷对话框 -->
    <el-dialog title="修改试卷" v-model="editDialogVisible" width="40%">
      <el-form :model="editForm" label-width="80px" :rules="formRules" ref="editFormRef">
        <el-form-item label="试卷标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editForm.description" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="试题" prop="questionIds">
          <el-select
            v-model="editForm.questionIds"
            multiple
            placeholder="请选择试题"
            style="width: 100%"
          >
            <el-option
              v-for="question in questionStore.questions"
              :key="question.id"
              :label="question.title"
              :value="question.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="草稿" value="DRAFT"></el-option>
            <el-option label="已发布" value="PUBLISHED"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePaper" :icon="Edit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Plus, Edit, Delete, Check } from '@element-plus/icons-vue';
import { usePaperStore, Paper, PaperCreateRequest, PaperUpdateRequest } from '@/stores/api/paper';
import { useQuestionStore } from '@/stores/api/question';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

const paperStore = usePaperStore();
const questionStore = useQuestionStore();

const statusMap = {
  DRAFT: '草稿',
  PUBLISHED: '已发布',
};

const createDialogVisible = ref(false);
const editDialogVisible = ref(false);

const createForm = ref<PaperCreateRequest>({
  title: '',
  description: '',
  questionIds: [],
});

const editForm = ref<PaperUpdateRequest>({
  id: 0,
  title: '',
  description: '',
  questionIds: [],
  status: 'DRAFT',
});

const formRules = ref<FormRules>({
  title: [{ required: true, message: '请输入试卷标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  questionIds: [
    {
      required: true,
      type: 'array',
      min: 1,
      message: '请至少选择一个试题',
      trigger: 'change',
    },
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
});

const createFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const showCreateDialog = () => {
  createForm.value = { title: '', description: '', questionIds: [] };
  createDialogVisible.value = true;
};

const showEditDialog = (paper: Paper) => {
  editForm.value = { ...paper, id: paper.id, status: paper.status };
  editDialogVisible.value = true;
};

const createPaper = async () => {
  if (!createFormRef.value) return;
  createFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await paperStore.createPaper(createForm.value);
        createDialogVisible.value = false;
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

const updatePaper = async () => {
  if (!editFormRef.value) return;
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await paperStore.updatePaper(editForm.value);
        editDialogVisible.value = false;
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

const publishPaper = async (id: number) => {
  try {
    await paperStore.publishPaper(id);
  } catch (error) {
    // 错误已在 store 中处理
  }
};

onMounted(() => {
  paperStore.fetchPapers();
  questionStore.fetchQuestions();
});
</script>

<style scoped>
.paper-manage {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}

.el-button i + span {
  margin-left: 8px;
}

.el-select,
.el-input {
  width: 100%;
}
</style>